package com.qiantu.phone.widget.setting;

import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.hjq.base.DensityUtils;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.QueryCodeResultBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.WheelValueBean;
import com.qiantu.phone.ui.dialog.BottomWheelViewDialog;
import com.lxj.xpopup.XPopup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static android.util.TypedValue.COMPLEX_UNIT_PX;

public class DeviceSettingTriggerMode extends SettingBar implements View.OnClickListener {
    private DeviceBean mDevice;
    private AppActivity mContext;
    private String queryCode;
    private int totalTime = 20 * 1000;
    private long startTime;
    private Handler mHandler;
    private WheelValueBean selectedValue;
    private Integer sensortriggtype;

    public DeviceSettingTriggerMode(AppActivity context, DeviceBean deviceBean) {
        this(context, null, deviceBean);
    }

    public DeviceSettingTriggerMode(AppActivity context, AttributeSet attrs, DeviceBean deviceBean) {
        this(context, attrs, 0, deviceBean);
    }

    public DeviceSettingTriggerMode(AppActivity context, AttributeSet attrs, int defStyleAttr, DeviceBean deviceBean) {
        this(context, attrs, defStyleAttr, R.style.setting_item_style, deviceBean);
    }

    public DeviceSettingTriggerMode(@NonNull AppActivity context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes, DeviceBean deviceBean) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mDevice = deviceBean;
        mContext = context;
        setLeftText(R.string.trigger_mode);
        setRightTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor2));
        sensortriggtype = mDevice.getStateData().getSettings().getSensortriggtype();
        if(sensortriggtype != null){
            switch (sensortriggtype){
                case 0:
                    setRightText(R.string.high_electrical_level);
                    break;
//                case 1:
//                    setRightText(R.string.low_electrical_level);
//                    break;
                case 2:
                    setRightText(R.string.pwm);
                    break;
            }
        }
        setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        setRightTextSize(COMPLEX_UNIT_PX, DensityUtils.dip2px(context, 12));
        if("0x2502".equals(mDevice.getProductModel())){
            setRightDrawableSize(1);
        }
        setOnClickListener(this::onClick);
    }

    private BottomWheelViewDialog dialog;
    private void showDialog(){
        if (dialog == null){
            dialog = new BottomWheelViewDialog(mContext, getData());
            dialog.setLabel(getResources().getString(R.string.trigger_mode));
            dialog.setDialogClickListener(new BottomWheelViewDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(WheelValueBean wheelValue) {
                    dialog.dismiss();
                    selectedValue = wheelValue;
                    changeType();
                }
            });
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(dialog);
        }
        if(sensortriggtype == null){
            dialog.setCurItem("0");
        }else{
            dialog.setCurItem(sensortriggtype + "");
        }
        dialog.show();
    }

    private List<WheelValueBean> getData(){
        List<WheelValueBean> items = new ArrayList<>();
        for (int i=0; i<3; i++){
            WheelValueBean bean = null;
            switch (i){
                case 0:
                    bean = new WheelValueBean(getResources().getString(R.string.high_electrical_level), i + "");
                    items.add(bean);
                    break;
//                case 1:
//                    bean = new WheelValueBean(getResources().getString(R.string.low_electrical_level), i + "");
//                    items.add(bean);
//                    break;
                case 2:
                    bean = new WheelValueBean(getResources().getString(R.string.pwm), i + "");
                    items.add(bean);
                    break;
            }
        }
        return items;
    }

    private Runnable countRunnable = new Runnable() {
        @Override
        public void run() {
            if(System.currentTimeMillis() - startTime > totalTime){
                handleFailed();
            }else{
                postDelayed(this, 990);
            }
        }
    };

    private void changeType() {
        startTime = System.currentTimeMillis();
        post(countRunnable);
        Map<String, Object> stateData = new HashMap<>();
        Map<String, Object> settings = new HashMap<>();
        settings.put("sensortriggtype", selectedValue.getValue());
        stateData.put("settings", settings);
        LLHttpManager.sendDeviceSetting(mContext, mDevice.getDeviceSerialNo(), stateData, new HttpCallback<HttpData<QueryCodeResultBean<String, Object>>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity)getContext()).showDialog(getResources().getString(R.string.setting));
                }
            }

            @Override
            public void onSucceed(HttpData<QueryCodeResultBean<String, Object>> result) {
                handleResult(result.getData());
            }

            @Override
            public void onFail(Exception e) {
                handleFailed();
            }

            @Override
            public void onEnd(Call call) {

            }
        });
    }

    private void querySendDeviceSetting(){
        LLHttpManager.querySendDeviceSetting(mContext, queryCode, new HttpCallback<HttpData<QueryCodeResultBean<String, Object>>>(null){
            @Override
            public void onStart(Call call) {
            }

            @Override
            public void onSucceed(HttpData<QueryCodeResultBean<String, Object>> result) {
                handleResult(result.getData());
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
                handleFailed();
            }

            @Override
            public void onEnd(Call call) {
            }
        });
    }

    private void handleResult(QueryCodeResultBean data){
        queryCode = data.getQueryCode();
        //发起操作:0 正在操作:1 操作成功:2 操作失败:3 操作异常:4 停止操作:5
        if(data != null){
            switch (data.getQueryStateType()){
                case 0:
                case 1:
                    if(mHandler == null){
                        mHandler = new Handler();
                    }
                    mHandler.postDelayed(pollingRunnable, 1000);
                    break;
                case 2:
                    if(mHandler != null){
                        mHandler.removeCallbacksAndMessages(null);
                    }
                    hideDialog();
                    setRightText(selectedValue.getLabel());
                    ToastUtils.show(R.string.set_success);
                    break;
                case 3:
                case 4:
                case 5:
                    handleFailed();
                    break;
            }
        }
    }

    private void handleFailed(){
        if(mHandler != null){
            mHandler.removeCallbacksAndMessages(null);
        }
        ToastUtils.show(R.string.set_failed);
        hideDialog();
    }

    private Runnable pollingRunnable = new Runnable(){
        @Override
        public void run() {
            querySendDeviceSetting();
        }
    };

    private void hideDialog(){
        if(getContext() != null && getContext() instanceof AppActivity){
            ((AppActivity)getContext()).hideDialog();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if(mHandler != null){
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onClick(View v) {
        if("0x2502".equals(mDevice.getProductModel())){
            return;
        }
        showDialog();
    }
}
